package cn.itsource.xhy.org.controller;

import cn.itsource.xhy.org.domain.Department;
import cn.itsource.xhy.org.query.DepartmentQuery;
import cn.itsource.xhy.org.service.IDepartmentService;
import cn.itsource.xhy.utils.AjaxResult;
import cn.itsource.xhy.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*@CrossOrigin*/
@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @PutMapping // put请求添加和修改，在参数中加上@RequestBody注解接收json格式数据，转换成对象
    public AjaxResult saveOrUpdate(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.save(department);
            } else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}") // delete请求，删除，注解后面加上("/{id}")，地址栏中的占位符，  在参数中加上@PathVariable("id")，传递id
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            departmentService.del(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败" + e.getMessage());
        }
    }

    @GetMapping("/{id}") // get请求，查单个，注解后面加上("/{id}")，地址栏中的占位符，   在参数中加上@PathVariable("id")，传递id
    public Department findById(@PathVariable("id") Long id){
        try {
            return departmentService.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @GetMapping  // get请求，查所有
    public List<Department> findAll(){
        try {
            return departmentService.findAll();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping
    public QueryResult<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            departmentService.patchDel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败" + e.getMessage());
        }
    }

}
